<?php


namespace app\admin\model;

use think\facade\Cache;

class Route extends Base
{
    public $routeCacheName = 'adminRouteCache';

    /**
     * Desc: 获取状态码缓存公共方法
     * User: 苏鹏
     * Date: 2023/9/7
     * Time: 16:18
     * @return void
     */
    public function getAdminModelCache(string $type = 'get') : array
    {
        switch ($type){
            case 'get' :
                $cache_res = Cache::get($this->routeCacheName);
                if($cache_res == false){
                    //生成缓存
                    $result = $this->getRouteListToCache();
                    return $result;
                }
                return $cache_res;
            case 'set' :
                $result = $this->getRouteListToCache();
                return $result;
            case 'del' :
                Cache::delete($this->routeCacheName);
                break;
        }
    }

    /**
     * Desc: 获取路由缓存公共方法 辅助类
     * User: 苏鹏
     * Date: 2023/9/20
     * Time: 10:12
     */
    public function getRouteListToCache()
    {
        $result = $this->where('status', 1)
            ->field('id,title,rule,route,method,vue_route,pid,is_emnu,english_title')
            ->order('pid asc')
            ->select()
            ->toArray();
        //多语言切换
        if(request()->header('lang') == 'en_us'){
            foreach($result as $k=>$v){
                $result[$k]['title'] = $v['english_title'];
            }
        }
        Cache::set($this->routeCacheName, $result);
        return $result;
    }


    /**
     * $is_emnu 0:返回全部路由信息，1：返回为菜单的路由信息
     * Desc: 树结构列表
     * User: 苏鹏
     * Date: 2023/9/21
     * Time: 9:34
     * @return void
     */
    public function getRouteTreeLists(int $is_emnu = 0)
    {

        $route_list = $this->getAdminModelCache('set');
        //只返回菜单is_emnu == 1
        $items = [];
        foreach($route_list as $value)
        {
            if($is_emnu == 1)
            {
                //只返回为菜单的路由
                if($value['is_emnu'] == 1)
                {
                    $items[$value['id']] = $value;
                }
            }else{
                $items[$value['id']] = $value;
            }

        }
        //第二部 遍历数据 生成树状结构
        $tree = [];
        foreach($items as $key => $item)
        {
            if(isset($items[$item['pid']]))
            {
                $items[$item['pid']]['children'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }



}